package com.design;

import java.util.HashMap;
import java.util.Map;

/**
 * 中央渠道（管理多个观察者）
 */
public class CentralSubject {
    private Map<String,ChannelSubject> channelMap=new HashMap<>();

    /**
     * 获取渠道
     */
    public ChannelSubject getChannelSubject(String channelName){
        return channelMap.computeIfAbsent(channelName,ChannelSubject::new);
    }

    /**
     * 添加订阅者
     * */
     public void addSubscriber(String channelName,Subscriber subscriber){
        getChannelSubject(channelName).subscribe(subscriber);
     }

     /**
      * 取消订阅者
      */
     public void unsubscribe(String channelName,Subscriber subscriber){
        getChannelSubject(channelName).unsubscribe(subscriber);
     }

     /**
      * 发布消息
      */
     public void publish(String channelName,String message){
         ChannelSubject channelSubject = getChannelSubject(channelName);
         if(channelSubject!=null){
             channelSubject.publish(message);
         }else{
             throw new RuntimeException("渠道不存在"+channelName);
         }
     }
}
